<template>
  <PageWrapper>
    <div ref="searchForm">
      <div style="border-bottom: 1px solid #eee; padding-bottom: 10px; font-size: 16px">
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </div>
      <div class="mt-2">
        <BasicForm
          ref="form"
          @submit="handleSubmit"
          @reset="handleReset"
          @register="registerForm"
        />
      </div>
    </div>

    <iframe
      v-if="iframeSrc"
      @load="iframeLoad"
      :src="iframeSrc"
      :style="{ width: '100%', height: `${reportPros.height}` }"
    ></iframe>
    <!-- 报表 -->
  </PageWrapper>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsCarddReportZcmxUreportView',
  });
</script>
<script setup lang="ts">
  import { defineComponent, ref, onMounted } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/src/components/Form';
  import { useI18n } from '/src/hooks/web/useI18n';
  import { PageWrapper } from '/src/components/Page';
  import { formSchemas } from '/src/utils/custom';
  import { formSet } from '/src/api/test/testData';
  import { router } from '/src/router';
  import { Icon } from '/src/components/Icon';
  import { useGlobSetting } from '/src/hooks/setting';

  import { useLoading } from '/src/components/Loading';
  import { useDict } from '/src/components/Dict';

  const { initDict, getDictLabel } = useDict();

  const { t } = useI18n('report.ureportView');
  const { ctxPath } = useGlobSetting();
  let defaultValue = ref<any>();
  let iframeSrc = ref<string>();
  let searchForm = ref<any>();
  let form = ref<any>();
  const formKey = ref('');
  const getTitle = ref({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.meta.title || t('统计报表'),
  });
  let reportPros = ref<any>({
    height: '', //iframe高度
    fileName: '', //文件名
    url: '', // 通用地址
    _t: '', // 显示按钮
  });
  //配置表单内容
  const schemas = ref<FormSchema[]>();
  const baseSchemas = [
    {
      label: t('用车单位'),
      field: 'dwbm',
      fieldLabel: 'dwqc',
      component: 'Select',
      componentProps: ({ formModel }) => {
        return {
          // selectType: 'basCusSelect',
          dictType: 'car_report_zcmx',
          allowClear: true,
          onSelect: async (values) => {
            const dictLabel = values.value;
            formKey.value = dictLabel;
            if (!dictLabel) {
              setProps({
                schemas: baseSchemas,
              });
              return;
            }
            reloadData(dictLabel);
          },
        };
      },
      dynamicRules: () => {
        return [
          {
            required: true,
            validator: (_, value) => {
              if (!formKey.value) {
                return Promise.reject('该单位未设置报表模板！');
              }
              return Promise.resolve();
            },
          },
        ];
      },
    },
  ] as FormSchema[];
  const [registerForm, { getFieldsValue, validate, setProps, setFieldsValue }] = useForm({
    labelWidth: 90,
    showActionButtonGroup: true,
    baseColProps: { lg: 6, md: 8 },
    showAdvancedButton: true,
    compact: true,
  });

  const [openFullLoading, closeFullLoading] = useLoading({
    tip: '加载中...',
  });

  // 获取uuid
  function generateUUID() {
    let d = new Date().getTime();
    let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
    });
    return uuid;
  }

  // iframe加载完成
  function iframeLoad() {
    closeFullLoading();
  }

  // 重置
  function handleReset() {
    setFieldsValue(defaultValue.value);
  }

  // 查询
  function handleSubmit() {
    reportPros.value.height = document.documentElement.clientHeight * 0.72 + 'px';
    openFullLoading();
    let url = reportPros.value.url;
    schemas.value?.forEach((item) => {
      if (form.value.formModel[item.field] && item.component != 'RangePicker') {
        url += `&${item.field}=${form.value.formModel[item.field]}`;
      }
      if (item.component == 'RangePicker' && form.value.formModel[item.field]) {
        url += `&${item.field}_gte=${form.value.formModel[item.field][0]}&${item.field}_lte=${
          form.value.formModel[item.field][1]
        }`;
      }
    });
    iframeSrc.value = url + `&key=${generateUUID()}&_t=${reportPros.value._t}`;
  }

  onMounted(() => {
    setProps({
      schemas: baseSchemas,
    });
    initDict(['car_report_zcmx']);
  });

  // 进入页面获取数据
  async function reloadData(viewCode: string) {
    const formRes = await formSet({ viewCode: viewCode });
    const configSchemas = formSchemas(formRes.layVoucherView.formTabs[0].colList, 3, {});
    schemas.value = [...baseSchemas, ...configSchemas];
    reportPros.value.fileName = formRes.layVoucherView.formConfig.formTitle;
    reportPros.value.url = `${ctxPath}/ureport/preview?_u=file:${reportPros.value.fileName}.ureport.xml&_n=${getTitle.value.value}`;
    reportPros.value._t = formRes.layVoucherView.formConfig.bpmFormKey;
    await setProps({
      schemas: schemas.value,
    });
  }
</script>
